/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.action.retrieve;

import com.inspur.edp.bef.api.action.assembler.IMgrActionAssembler;
import com.inspur.edp.bef.api.be.IBEManagerContext;
import com.inspur.edp.bef.api.be.IBusinessEntity;
import com.inspur.edp.bef.core.be.BusinessEntity;
import com.inspur.edp.bef.spi.action.AbstractManagerAction;
import com.inspur.edp.cef.api.dataType.entity.ICefRootEntity;
import com.inspur.edp.cef.entity.changeset.ChangeType;
import com.inspur.edp.cef.entity.changeset.IChangeDetail;

public class IsEffectiveMgrAction extends AbstractManagerAction<Boolean> {

  // region Consturctor
  private String nodeCode;
  private String dataId;

  public IsEffectiveMgrAction(IBEManagerContext managerContext, String nodeCode, String dataId) {
    super(managerContext);
    super.isReadOnly=true;
    this.nodeCode = nodeCode;
    this.dataId = dataId;
  }

  // endregion 字段属性

  // region Override

@Override
  protected final IMgrActionAssembler getMgrAssembler() {
    return null;
  }

  @Override
  public final void execute() {
    IChangeDetail change = getChange();
    // 如果没有变更或者是修改的变更则从持久化判断
    if (change == null || change.getChangeType() == ChangeType.Modify) {
      setResult(getBEManagerContext().getBEManager().getRepository().isEffective(nodeCode, dataId));
    }
    // 否则说明有变更且不是修改, 那么只能是新增或删除
    else {
      setResult(change.getChangeType() == ChangeType.Added);
    }
  }

  private IChangeDetail getChange() {
ICefRootEntity entity =
        (BusinessEntity) getBEManagerContext().getBEManager().createSessionlessEntity("");
    if (isRoot()) {
      return getRootChange();
    } else {
      return getChildChange();
    }
  }

  private IChangeDetail getRootChange() {
IBusinessEntity entity = getBEManagerContext().getEntity(dataId);
    return entity.getBEContext().getCurrentTransactionalChange();
  }

private boolean isRoot() {
    return nodeCode.equals(
        (((BusinessEntity) getBEManagerContext().getBEManager().createSessionlessEntity(""))
            .getNodeCode()));
  }

  private IChangeDetail getChildChange() {
    // TODO: 不是主表则可能是子表或者从从表, 暂时先不走缓存直接从持久化读;
    return null;
  }

  // endregion
}
